import java.util.*;

// 我好想逃却逃不掉
public class escape {

    static int N, M;
    static char[][] maze;
    static boolean[][] visited;
    static int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // 上下左右

    public static int solution(int N, int M, char[][] data) {
        escape.N = N;
        escape.M = M;
        maze = data;
        visited = new boolean[N][M];

        // 找到出口位置
        int[] exit = findExit();
        if (exit == null) return N * M; // 如果没有出口，所有位置都无法到达

        // 从出口开始反向BFS
        bfs(exit[0], exit[1]);

        // 统计无法到达出口的位置数量
        int count = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if (!visited[i][j]) count++;
            }
        }
        return count;
    }

    private static int[] findExit() {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if (maze[i][j] == 'O') return new int[]{i, j};
            }
        }
        return null;
    }

    private static void bfs(int startX, int startY) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{startX, startY});
        visited[startX][startY] = true;

        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int x = current[0], y = current[1];

            // 检查四个方向
            for (int[] dir : directions) {
                int nx = x + dir[0], ny = y + dir[1];
                if (isValid(nx, ny) && !visited[nx][ny]) {
                    if (maze[nx][ny] == '.' || maze[nx][ny] == 'O') {
                        visited[nx][ny] = true;
                        queue.offer(new int[]{nx, ny});
                    } else if (canReach(nx, ny, x, y)) {
                        visited[nx][ny] = true;
                        queue.offer(new int[]{nx, ny});
                    }
                }
            }
        }
    }

    private static boolean isValid(int x, int y) {
        return x >= 0 && x < N && y >= 0 && y < M;
    }

    private static boolean canReach(int x, int y, int targetX, int targetY) {
        char c = maze[x][y];
        if (c == 'U' && x - 1 == targetX && y == targetY) return true;
        if (c == 'D' && x + 1 == targetX && y == targetY) return true;
        if (c == 'L' && x == targetX && y - 1 == targetY) return true;
        if (c == 'R' && x == targetX && y + 1 == targetY) return true;
        return false;
    }

    public static void main(String[] args) {
        char[][] pattern = {
                {'.', '.', '.', '.', '.'},
                {'.', 'R', 'R', 'D', '.'},
                {'.', 'U', '.', 'D', 'R'},
                {'.', 'U', 'L', 'L', '.'},
                {'.', '.', '.', '.', 'O'}
        };
        System.out.println(solution(5, 5, pattern) == 10);
    }
}
